package com.sinodata.bsm.cicp.collector.sqlserver;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.AbstractJDBCCollector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.DBConnectionUtil;
import com.sinodata.bsm.common.constants.SeparatorConstants;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class FileGroup extends AbstractJDBCCollector {
    private static final Logger logger = Logger.getLogger(FileGroup.class);

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        try {
            String[] propMetas = getPropMeta();
            String serverName = this.getParamMap().get("ServerName");
            String sql = "sp_helpdb";
            String[] rs = this.getStrings(serverName, sql, ip);
            ResPropertyValue propertyValueX = new ResPropertyValue();
            ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
            for (int i = 0; i < propMetas.length; i++) {
                propValues[i] = ResPropertyValue.createPropValue(rs[i], propMetas[i]);
            }
            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
        } catch (Exception e) {
            logger.error("failed to collect sqlserver File Group", e);
            throw new CollectorException(e);
        }
        return values;
    }

    @SuppressWarnings("unchecked")
    private String[] getStrings(String serverName, String sql, String ip) throws CollectorException {
        String[] propValArr = new String[6];
        CallableStatement cstmt = null;
        Statement stmt = null;
        ResultSet rst = null;
        Connection conn = null;
        try {
            conn = DBConnectionUtil.getInstance().getConnection("sqlserver", ip, serverName);
            if (conn == null) {
                return null;
            }
            cstmt = conn.prepareCall(sql);
            cstmt.setQueryTimeout(10);
            rst = cstmt.executeQuery();
            List dbnameList = new ArrayList();
            if (rst != null) {
                while (rst.next()) {
                    dbnameList.add(rst.getString(1));
                }
            }

            Iterator it = dbnameList.iterator();
            String dbname = "";
            while (it.hasNext()) {
                dbname = it.next().toString();

                List fgnameList = new ArrayList();
                sql = dbname + ".dbo.sp_helpfilegroup";
                cstmt = conn.prepareCall(sql);
                rst = cstmt.executeQuery();
                if (rst != null) {
                    while (rst.next()) {
                        String name = rst.getString(1);
                        fgnameList.add(name);
                    }
                }
                Iterator fgit = fgnameList.iterator();
                while (fgit.hasNext()) {
                    String fgname = fgit.next().toString();
                    //文件个数
                    int fileCount = 0;
                    String fgsql = "{call " + dbname + ".dbo.sp_helpfilegroup(?)}";
                    cstmt = conn.prepareCall(fgsql);
                    cstmt.setString(1, fgname);
                    rst = cstmt.executeQuery();
                    if (rst != null) {
                        rst.next();
                        fileCount = rst.getInt(3);
                    }
                    //数据文件详细信息
                    StringBuffer fileDetail = new StringBuffer();
                    cstmt.getMoreResults();
                    rst = cstmt.getResultSet();
                    if (rst != null) {
                        while (rst.next()) {
                            String line = getTabLineStr(rst, 6);
                            fileDetail.append(line).append(SeparatorConstants.LIN_SEPARATOR);
                        }
                    }
                    String fileDetailstr = fileDetail.toString();
                    propValArr[0] = fileCount + "";
                    propValArr[1] = fileDetailstr;
                }
            }

        } catch (Exception ex) {
            logger.error("while connect database : ", ex);
            throw new CollectorException(ex);
        } finally {
            if (cstmt != null) {
                try {
                    cstmt.close();
                } catch (SQLException e1) {
                }
            }
            if (rst != null)
                try {
                    rst.close();
                } catch (SQLException e1) {
                }
            if (stmt != null)
                try {
                    stmt.close();
                } catch (SQLException e1) {
                }
            DBConnectionUtil.getInstance().returnConnection(conn);
        }
        return propValArr;
    }

    private String getTabLineStr(ResultSet rst, int colNum) throws CollectorException {
        StringBuffer tabLineStr = new StringBuffer();
        try {
            for (int i = 1; i <= colNum; i++) {
                String val = rst.getString(i);
                if (val == null || val.trim().length() == 0) {
                    val = " ";
                } else
                    val = val.trim();
                tabLineStr.append(val).append(SeparatorConstants.COL_SEPARATOR);
            }
        } catch (Exception e) {
            logger.error("failed to get TabLineStr", e);
            throw new CollectorException(e);
        }
        return tabLineStr.toString();
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "ServerName" };
    }

    @Override
    public String[] getPropMeta() {
        return new String[] { "DataFiles", "DataFilesDetailedInfo" };
    }

}
